package com.keshi.openplatform.payment.controller;

import com.keshi.openplatform.payment.event.PaymentEvent;
import com.keshi.openplatform.payment.utils.PayCommonUtil;
import com.keshi.openplatform.payment.utils.PayConfigUtil;
import com.keshi.openplatform.payment.utils.XMLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;

@RequestMapping("/result")
@RestController
public class ResultController {
    @Autowired
    private ApplicationContext applicationContext;


    @RequestMapping("/payresult")
    public String processResult(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("收到微信给我们发送的请求了");
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            StringBuilder builder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);//将微信传递给我们的数据转成字符串
            }


            Map<String,String> map = XMLUtil.doXMLParse(builder.toString());//将微信的数据转成map

            TreeMap treeMap = new TreeMap();
//            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
//                String key = stringStringEntry.getKey();
//                String value = stringStringEntry.getValue();
//                if ()
//            }
            treeMap.putAll(map);

            if (PayCommonUtil.isTenpaySign("UTF-8",treeMap, PayConfigUtil.API_KEY)) {
                //代表签名校验成功
                String oid = map.get("out_trade_no");//我们的订单号
                System.err.println("订单号:" + oid + "支付成功了");
                //实际开发中行此处需要更新相关信息

                PaymentEvent paymentEvent = new PaymentEvent();
                paymentEvent.setOid(oid);
                paymentEvent.setToltalPrice(Integer.parseInt(map.get("total_fee")));

                applicationContext.publishEvent(paymentEvent);
                //返回数据给微信

                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml>";
            }

        } catch (Exception e) {

        }
        return "success";//返回除了上面的xml外都不行,都是失败
    }
}
